/*
 * Copyright 2011 PA Consulting Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.prodeagle.java.counters;

import java.util.Date;

import com.prodeagle.java.ProdEagleConstants;

/**
 * A set of methods for managing counter times
 * 
 * @author Edward Hartwell Goose
 *
 */
public class CounterUtil implements ProdEagleConstants {
	
	private static CounterNamesManager cnm = null;
	
	/**
	 * Get an instance of the CounterNamesManager
	 * @return - a counter names manager
	 */
	public static CounterNamesManager getDefaultCounterNamesManager() {
		//if the CounterNamesManager is null, or the current one was created over 1 day ago, get a new one
		if (null == cnm || (new Date().getTime() - 1000 * 60 * 60 * 24) > cnm.creationTime) {
			cnm = new CounterNamesManager();
		}
		
		return cnm;
	}

	/**
	 * Get's the current time in milliseconds modified down to the nearest slot size (defaults to one minute)
	 * 
	 * @return - a rounded epoch time (in milliseconds)
	 */
	public static long getEpochRounded() {
		return getEpochRounded(null, MIN_SLOT_SIZE);
	}
	
	/**
	 * Get's the input time (or current time) rounded down to the nearest minute
	 * 
	 * @param utcDatetime - a date (or null)
	 * @param slotSize - the slot size
	 * @return - a rounded epoch time (in milliseconds)
	 */
	public static long getEpochRounded(Date utcDatetime, int slotSize) {
		if (null == utcDatetime) {
			utcDatetime = new Date();
		}
		
		long epoch = utcDatetime.getTime();
		
		return epoch - (epoch % slotSize);
	}
}
